In Svelte, the onDestroy lifecycle hook runs just before a component is removed from the DOM. It is primarily used for cleanup tasks, such as unsubscribing from services, clearing timers, or removing event listeners to prevent memory leaks.
Clearing setInterval or setTimeout timers.
Unsubscribing from external data sources or services.
Removing custom event listeners added to the DOM or window.
Cleaning up third-party library instances.
Releasing resources to avoid memory leaks.
In this example, the onDestroy hook clears the interval when the component is destroyed, ensuring that no unnecessary code runs in the background.
onDestroy ensures that the event listener is properly removed when the component is destroyed, preventing memory leaks and unexpected behavior.
onDestroy runs just before the component is removed from the DOM.
It is used to clean up resources, such as timers, event listeners, or external subscriptions.
Helps prevent memory leaks in long-running applications.
Always pair onMount setup logic with onDestroy cleanup logic when needed.